// 获取画布和上下文
const canvas = document.getElementById('game-canvas');
const ctx = canvas.getContext('2d');

// 画布尺寸
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 600;
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;

// 金币
let coins = 100;
const coinsElement = document.getElementById('coins');

// 路径点
const pathPoints = [
    { x: 0, y: CANVAS_HEIGHT / 2 },
    { x: CANVAS_WIDTH / 3, y: CANVAS_HEIGHT / 2 },
    { x: CANVAS_WIDTH / 3, y: CANVAS_HEIGHT / 4 },
    { x: 2 * CANVAS_WIDTH / 3, y: CANVAS_HEIGHT / 4 },
    { x: 2 * CANVAS_WIDTH / 3, y: 3 * CANVAS_HEIGHT / 4 },
    { x: CANVAS_WIDTH, y: 3 * CANVAS_HEIGHT / 4 }
];

// 敌人数组
let enemies = [];

// 塔数组
let towers = [];

// 敌人构造函数
function Enemy() {
    this.x = pathPoints[0].x;
    this.y = pathPoints[0].y;
    this.speed = 2;
    this.health = 100;
    this.width = 20;
    this.height = 20;
    this.color = 'red';
    this.pathIndex = 0;
}

// 塔构造函数
function Tower(x, y) {
    this.x = x;
    this.y = y;
    this.range = 100;
    this.damage = 20;
    this.fireRate = 1; // 每秒射击次数
    this.lastShotTime = 0;
    this.width = 30;
    this.height = 30;
    this.color = 'blue';
}

// 绘制路径
function drawPath() {
    ctx.beginPath();
    ctx.moveTo(pathPoints[0].x, pathPoints[0].y);
    for (let i = 1; i < pathPoints.length; i++) {
        ctx.lineTo(pathPoints[i].x, pathPoints[i].y);
    }
    ctx.strokeStyle = 'green';
    ctx.lineWidth = 5;
    ctx.stroke();
}

// 绘制敌人
function drawEnemies() {
    enemies.forEach(enemy => {
        ctx.beginPath();
        ctx.fillStyle = enemy.color;
        ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
        ctx.closePath();
    });
}

// 绘制塔
function drawTowers() {
    towers.forEach(tower => {
        ctx.beginPath();
        ctx.fillStyle = tower.color;
        ctx.fillRect(tower.x - tower.width / 2, tower.y - tower.height / 2, tower.width, tower.height);
        ctx.closePath();
    });
}

// 移动敌人
function moveEnemies() {
    for (let i = enemies.length - 1; i >= 0; i--) {
        const enemy = enemies[i];
        const targetPoint = pathPoints[enemy.pathIndex];
        const dx = targetPoint.x - enemy.x;
        const dy = targetPoint.y - enemy.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        if (distance < enemy.speed) {
            enemy.pathIndex++;
            if (enemy.pathIndex === pathPoints.length) {
                enemies.splice(i, 1);
                continue;
            }
        } else {
            const angle = Math.atan2(dy, dx);
            enemy.x += enemy.speed * Math.cos(angle);
            enemy.y += enemy.speed * Math.sin(angle);
        }
    }
}

// 塔攻击敌人
function towerAttack() {
    const currentTime = Date.now();
    towers.forEach(tower => {
        if (currentTime - tower.lastShotTime >= 1000 / tower.fireRate) {
            let targetEnemy = null;
            let minDistance = Infinity;
            enemies.forEach(enemy => {
                const dx = enemy.x - tower.x;
                const dy = enemy.y - tower.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                if (distance <= tower.range && distance < minDistance) {
                    minDistance = distance;
                    targetEnemy = enemy;
                }
            });
            if (targetEnemy) {
                targetEnemy.health -= tower.damage;
                if (targetEnemy.health <= 0) {
                    const index = enemies.indexOf(targetEnemy);
                    if (index!== -1) {
                        enemies.splice(index, 1);
                        coins += 20;
                        coinsElement.textContent = coins;
                    }
                }
                tower.lastShotTime = currentTime;
            }
        }
    });
}

// 创建敌人
function createEnemy() {
    if (Math.random() < 0.01) {
        enemies.push(new Enemy());
    }
}

// 处理鼠标点击事件，放置塔
canvas.addEventListener('click', function (event) {
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    if (coins >= 50) {
        towers.push(new Tower(x, y));
        coins -= 50;
        coinsElement.textContent = coins;
    }
});

// 主游戏循环
function gameLoop() {
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    drawPath();
    drawEnemies();
    drawTowers();

    moveEnemies();
    towerAttack();
    createEnemy();

    requestAnimationFrame(gameLoop);
}

// 开始游戏循环
gameLoop();